# !/user/bin/env python3
# -*- encoding: utf-8 -*-

"""
    sentinel http 计算时间
"""

import json
import requests
import time

SESSION = requests.session()
server_name_list = []


def login():
    global SESSION
    data = {"username": "sentinel", "password": "sentinel"}
    headers = {
        "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:87.0) Gecko/20100101 Firefox/87.0"
    }
    response = SESSION.post("https://uat-sentinel.ezcun.com/auth/login", data, headers)
    if response.status_code == 200:
        print("登录成功：" + response.text)
    pass


def get_server_list():
    global SESSION
    global server_name_list
    response = SESSION.get("https://uat-sentinel.ezcun.com/app/briefinfos.json")
    if response.status_code == 200:
        res = json.loads(response.text)
        print("服务器如下：")
        for item in res["data"]:
            print(item["app"])
            server_name_list.append(item["app"])
            # item['machines']


def http_time():
    global SESSION
    app = input("请输入需要监控的服务器名称，默认(ezcun-cloud-org-admin-gateway）：")
    if app == "":
        app = "ezcun-cloud-org-admin-gateway"
    url = (
        "https://uat-sentinel.ezcun.com/metric/queryTopResourceMetric.json?app="
        + app
        + "&pageIndex=1&pageSize=200"
    )
    searhKey = input("请输入关键字过滤，没有就不要填：")
    if searhKey != "":
        url += "&searchKey=" + searhKey
    print("输入ctrl + c 关闭")

    while True:
        time.sleep(3)
        response = SESSION.get(url)
        if response.status_code == 200:
            res = json.loads(response.text)
            if res["data"] != None:
                if res["data"]["metric"] != None:
                    for key, uri in res["data"]["metric"].items():
                        rt_list = list(map(lambda x: int(x["rt"]), uri))
                        rt_list.sort(reverse=True)
                        print(key, "最长耗时：", rt_list[0])


if __name__ == "__main__":
    login()
    get_server_list()
    http_time()
